<template>
  <div class="app-container">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <!-- 商品名字 -->
      <el-form-item prop="name" label="商品名字">
        <el-input placeholder="请输入商品的名字" v-model="ruleForm.name" />
      </el-form-item>
      <!-- 商品分类选项 -->
      <el-form-item label="商品分类" prop="category">
        <el-select v-model="ruleForm.category" placeholder="请选择分类">
          <el-option
            v-for="item in categories"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <!-- 主图 上传文件 -->
      <el-form-item label="商品主图"
        ><el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl | dalImg" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload
      ></el-form-item>
      <!-- 商品价格 -->
      <el-form-item prop="price" label="商品价格">
        <el-input
          placeholder="请输入商品的价格"
          v-model.number="ruleForm.price"
        />
      </el-form-item>
      <!-- 商品库存 -->
      <el-form-item prop="amount" label="商品库存">
        <el-input
          placeholder="请输入商品的库存"
          v-model.number="ruleForm.amount"
        />
      </el-form-item>
      <!--  -->
      <el-form-item label="详情">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="html"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
          /></div
      ></el-form-item>
      <!-- 创建和重置按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {
  addModelAPI,
  loadModelByIdAPI,
  updataModelByIdAPI
} from '@/api/products'
import { uploadUrl } from '@/utils/request'
import { loadModelsAPI as loadCategories } from '@/api/product-categories' // as 作用是起一个别名
export default {
  components: { Editor, Toolbar },
  data() {
    return {
      ruleForm: {
        name: '',
        amount: '',
        price: '',
        category: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      imageUrl: '',
      uploadUrl,
      categories: [],
      // 富文本编辑器部分
      editor: null,
      html: '',
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default' // or 'simple'
    }
  },

  async created() {
    // id 存在调接口取数据，id不存在什么都不做
    if (this.$route.query.id) {
      // 点击修改的时候把原有的数据带过来
      const res = await loadModelByIdAPI(this.$route.query.id)
      this.ruleForm.name = res.name
      this.ruleForm.amount = res.amount
      this.ruleForm.price = res.price
      this.imageUrl = res.coverImage
      this.ruleForm.category = res.category?.id // 判断是否存在，存在就取，不存在就崩
      this.html = res.content
    }
    // 商品分类接口
    const res = await loadCategories()
    this.categories = res.data
  },
  methods: {
    // 创建
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 判断是修改还是新增
          if (this.$route.query.id) {
            // id 存在 调用修改api
            await updataModelByIdAPI(this.$route.query.id, {
              ...this.ruleForm,
              coverImage: this.imageUrl,
              content: this.html
            })
            this.$message.success('修改成功')
          } else {
            // id 不存在 调用新增api
            await addModelAPI({
              ...this.ruleForm,
              coverImage: this.imageUrl,
              content: this.html
            })
            this.$message.success('创建成功')
          }
          // this.$message.success('创建成功')
          this.$router.push({
            name: 'ProductList'
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 文件上成功后的回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data
      // console.log(res)
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    }
  },
  // mounted() {
  //   // 模拟 ajax 请求，异步渲染编辑器
  //   // setTimeout(() => {
  //   //   this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
  //   // }, 1500)
  // },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>
